package com.woniu.bank.service.impl;


import com.woniu.bank.dto.RoleDTO;
import com.woniu.bank.entity.SysRole;
import com.woniu.bank.mapper.SysRoleMapper;
import com.woniu.bank.mapper.SysRolePermissionMapper;
import com.woniu.bank.service.SysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Description: TODO
 * @Author: WangHeng
 * @Date: 2022/12/9 15:46
 */
@Service
public class SysRoleServiceImpl implements SysRoleService {
    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Autowired
    private SysRolePermissionMapper sysRolePermissionMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public List<Integer> getRolesByUser(Integer uid) {
        return sysRoleMapper.getRolesByUser(uid);
    }

    @Override
    public List<SysRole> getAllRoles() {
        Object role = redisTemplate.opsForValue().get("AllRole");
        if (role != null) {
            return (List<SysRole>) role;
        } else {
            redisTemplate.opsForValue().set("AllRole", sysRoleMapper.getAllRoles());
            return (List<SysRole>) redisTemplate.opsForValue().get("AllRole");
        }
    }

    /**
     * @Description 删除当前用户角色，赋予新的角色
     * @Para a
     * @Retun a
     * @Author WangMr
     * @Date Create by 2022/12/9 17:08
     */
    @Override
    @Transactional
    public int updateRoles(RoleDTO roleDTO) {
        sysRoleMapper.deleteRoleByUser(roleDTO.getUid());
        if (roleDTO.getRids() != null && roleDTO.getRids().length > 0) {
            sysRoleMapper.saveRoleByUser(roleDTO);
        }
        return 1;
    }

    @Override
    public List<Integer> getPermissionByRole(Integer rid) {
        return sysRolePermissionMapper.getPermissionByRole(rid);
    }

    @Override
    public int insertSelective(SysRole record) {
        return sysRoleMapper.insertSelective(record);
    }
}
